package com.api.gbhg.zengping.web;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.api.gbhg.lbj.tool.Tools;
import com.api.gbhg.zengping.common.res.Res;
import com.api.gbhg.zengping.dao.BudgeSourceDao;
import com.api.gbhg.zengping.dao.PropertyManagementCostDao;
import com.api.gbhg.zengping.page.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: gbhg-oa
 * @author: Mr.zeng
 * @create: 2020-12-25 16:22
 *
 * 物业核批查询列表
 **/
public class PropertyManagementAction {
    public static final Logger LOGGER = LoggerFactory.getLogger("gbhg");
    // 操作sql类
    private static final PropertyManagementCostDao rmcd=new PropertyManagementCostDao();

    /**
     * 物业核批查询列表
     * @param param
     * @return
     */
    @POST
    @Path("/getPropertyManagement")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String PropertyManagement(Map<String,String> param) {
         // 得到核批状态 3就是已核批  非3就是待核批
        final String requestId = param.get("requestId");
        LOGGER.info("物业核批列表参数："+requestId);
        RecordSetTrans rst = rmcd.getSBInfo(requestId);
        Map<String,Object>[] map=new HashMap[rst.getArray().size()];
        int i=0;
        while (rst.next()){
            map[i]=new HashMap<>();
            //mainid  判断相同的明细
            map[i].put("mianid",rst.getInt("mainid"));
            //序号id
            map[i].put("key",i);
            // 流程记录id
            map[i].put("lcjlsqjlid",rst.getString("lcjlsqjlid"));
            map[i].put("xmin",rst.getString("xmmin"));
            // 申报单位
            RecordSet sbdw = rmcd.getSBDWById(rst.getInt("sbdw"));
            sbdw.next();
            map[i].put("sbdw",sbdw.getString("SUBCOMPANYNAME"));
            // 申报科室
            RecordSet sbks = rmcd.getSBKSById(rst.getInt("sbks"));
            sbks.next();
            map[i].put("sbks",sbks.getString("departmentmark"));
            //编报人
            RecordSet jbr = rmcd.getUserNameById(rst.getInt("jbr"));
            jbr.next();
            String loginid = jbr.getString("loginid");
            if(loginid==""){
                loginid="系统管理员";
            }
            map[i].put("jbr",loginid);

            map[i].put("mjpf",rst.getString("mjpf"));
            //年度经费需求(万元)
            map[i].put("ndjfxqwy",rst.getString("ndjfxqwy"));
            // 管理费用 年  (*10000 转为元)  *10000
            Double glfwyn = rst.getDouble("glfwyn");
            BigDecimal b1=BigDecimal.valueOf(glfwyn);
            map[i].put("glfwyn",glfwyn);
            //保留两位小数
            BigDecimal divide = b1.divide(new BigDecimal(12),2, BigDecimal.ROUND_HALF_UP);
            //管理费用 月
            map[i].put("glfwyy",divide.doubleValue());
            // 合同期限年
           //map[i].put("htqxn",rst.getInt("htqxn"));
            // 合同期限时间
//            String htqdsj = rst.getString("htqdsj");
            LOGGER.info("================================="+rst.getString("htqxn")+"==================================================");
            // 因为取值 为 1.00 所以需要做转换、截取
//            String htqxn = rst.getString("htqxn");
//            map[i].put("htqdsj", DateUtil.getDateAddYear(htqdsj,Integer.valueOf(htqxn.substring(0,htqxn.indexOf(".")))));
            map[i].put("yszje",rst.getString("yszje"));
            //支付渠道
            map[i].put("zfqd","暂无");
            //功能科目
            map[i].put("gnkm","暂无");
            i++;
        }

        PageInfo<String> pageInfo=new PageInfo();
        String tableName="uf_wygljfbb"; //物业核批表名
        RecordSetTrans sbInfoCount = rmcd.getSBInfoCount(tableName,requestId);
        sbInfoCount.next();
        int pageCount = sbInfoCount.getInt("num");
        pageInfo.setTotal(pageCount);
        pageInfo.setList(map);
        pageInfo.setFromTable(tableName);
        return JSON.toJSONString(pageInfo);
    }

    /**
     * 物业核批查询列表----核批调用方法
     * @param requestId
     * @return
     */
    public String PropertyManagement1(String requestId) {
        // 得到核批状态 3就是已核批  非3就是待核批
//        final String requestId = param.get("requestId");
        LOGGER.info("物业核批列表参数："+requestId);
        RecordSetTrans rst = rmcd.getSBInfo(requestId);
        Map<String,Object>[] map=new HashMap[rst.getArray().size()];
        int i=0;
        while (rst.next()){
            map[i]=new HashMap<>();
            //mainid  判断相同的明细
            map[i].put("mianid",rst.getInt("mainid"));
            //序号id
            map[i].put("key",i);
            // 流程记录id
            map[i].put("lcjlsqjlid",rst.getString("lcjlsqjlid"));
            map[i].put("xmin",rst.getString("xmmin"));
            // 申报单位
            RecordSet sbdw = rmcd.getSBDWById(rst.getInt("sbdw"));
            sbdw.next();
            map[i].put("sbdw",sbdw.getString("SUBCOMPANYNAME"));
            // 申报科室
            RecordSet sbks = rmcd.getSBKSById(rst.getInt("sbks"));
            sbks.next();
            map[i].put("sbks",sbks.getString("departmentmark"));
            //编报人
            RecordSet jbr = rmcd.getUserNameById(rst.getInt("jbr"));
            jbr.next();
            String lastname = jbr.getString("lastname");
            if(StrUtil.isEmpty(lastname)){
                lastname="系统管理员";
            }
            map[i].put("jbr",lastname);
//            map[i].put("wyxm",rst.getString("wyxm"));
            //物业性质
//            map[i].put("wyxz",rst.getString("wyxz"));
            map[i].put("mjpf",rst.getString("mjpf"));
//            map[i].put("djypfm",rst.getString("djypfm"));
            //年度经费需求(万元)


            BigDecimal ndjfxqwy = new BigDecimal(rst.getString("ndjfxqwy"));
            map[i].put("ndjfxqwy",ndjfxqwy.divide(new BigDecimal("10000"),4, BigDecimal.ROUND_HALF_UP));
            // 管理费用 年  (*10000 转为元)  *10000

            BigDecimal glfwyn = new BigDecimal(rst.getString("glfwyn"));
            map[i].put("glfwyn",glfwyn.divide(new BigDecimal("10000"),4, BigDecimal.ROUND_HALF_UP));
            //保留两位小数
//            BigDecimal divide = b1.divide(new BigDecimal(12),4, BigDecimal.ROUND_HALF_UP);
            //管理费用 月
            BigDecimal djypfm = new BigDecimal(rst.getString("djypfm"));
            map[i].put("glfwyy", djypfm.divide(new BigDecimal("10000"),4, BigDecimal.ROUND_HALF_UP));
            // 合同期限年
            //map[i].put("htqxn",rst.getInt("htqxn"));
            // 合同期限时间
//            String htqdsj = rst.getString("htqdsj");
            LOGGER.info("================================="+rst.getString("htqxn")+"==================================================");
            // 因为取值 为 1.00 所以需要做转换、截取
//            String htqxn = rst.getString("htqxn");
//            map[i].put("htqdsj", DateUtil.getDateAddYear(htqdsj,Integer.valueOf(htqxn.substring(0,htqxn.indexOf(".")))));

            BigDecimal yszje = new BigDecimal(rst.getString("yszje"));
            map[i].put("yszje",yszje.divide(new BigDecimal("10000"),4, BigDecimal.ROUND_HALF_UP));
            //支付渠道
            map[i].put("zfqd","暂无");
            //功能科目
            map[i].put("gnkm","暂无");
            i++;
        }

        PageInfo<String> pageInfo=new PageInfo();
        String tableName="uf_wygljfbb"; //物业核批表名
        RecordSetTrans sbInfoCount = rmcd.getSBInfoCount(tableName,requestId);
        sbInfoCount.next();
        int pageCount = sbInfoCount.getInt("num");
        pageInfo.setTotal(pageCount);
        pageInfo.setList(map);
        pageInfo.setFromTable(tableName);
        return JSON.toJSONString(pageInfo);
    }


    /**
     * 物业批量审批接口  （同意，归档）
     * @param param
     * @return
     */
    @POST
    @Path("/batchApproval")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String batchApprovalArchive(Map<String,Integer[]> param){
        Integer[] lcjlid = param.get("lcjlid");
        rmcd.updateBatchApprovalArchive(lcjlid);
        return JSON.toJSONString(Res.ok(200,"成功"));
    }

    /**
     * 物业批量审批接口  （不同意，退回）
     * @param param
     * @return
     */
    @POST
    @Path("/batchApprovalFallBack")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String batchApprovalFallBack(Map<String,Integer[]> param){
        Integer[] lcjlid = param.get("lcjlid");
        rmcd.updateBatchApprovalFallBack(lcjlid);
        return JSON.toJSONString(Res.ok(200,""));
    }

    /**
     * 经费金额冻结
     * @param pageInfo
     * @return
     */
    @POST
    @Path("/moneyFreeze")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String moneyFreeze(PageInfo pageInfo){
        //报销流程创建的同时   新增一条明细记录 ,记录状态 待审核0
        addDetail(pageInfo.getList(),pageInfo.getFlowHeadLine(),pageInfo.getFlowId());
        boolean b = false;
        Map<String, String> map = new HashMap<>();
        try {
            b = rmcd.queryJingfei(pageInfo.getList(),map);
        } catch (Exception e) {
            e.printStackTrace();
        }
       if(b){
           map.put("success","ok");
            map.put("msg","成功");
        }else {
            map.put("success","error");
            map.put("msg","失败");
        }
        return JSON.toJSONString(map);
    }

    /**
     * 添加报销明细
     * @param mapDtl
     * @param flowHeadLine
     * @param bxFlowId
     */
   public static void addDetail(Map<String,String>[] mapDtl,String flowHeadLine,String bxFlowId){
        //计算报销总金额
        Double bxjeSum=0.00;
        RecordSet del = new RecordSet();
        for (int i = 0; i < mapDtl.length; i++) {

            //bxjeSum+=Double.valueOf(mapDtl[i].get("money"));
            // 添加一条明细
            String lcjlid = String.valueOf(mapDtl[i].get("lcjlid"));
            RecordSet rs = rmcd.queryJingfeiBylcjlId(lcjlid);
            if (rs.next()){
                Map<String,Object> param=new HashMap<>();
                param.put("mainid",rs.getInt("id"));
                param.put("bxje",mapDtl[i].get("money"));
                param.put("spzt",0);
                // 报销人
                String bxr = rs.getStringNoTrim("modedatamodifier");
                param.put("bxr",bxr);
                // 报销人部门
                RecordSet sbdw = rmcd.getSBKSById(Integer.valueOf(bxr));
                sbdw.next();
                String departmentmark = sbdw.getString("departmentmark");
                LOGGER.info("departmentmark----"+departmentmark);
                param.put("bxrbm", Tools.getbmyId(departmentmark));
                //经办部门
                param.put("jbbm","0");
                //经办人员
                param.put("jbry","0");
                //申请日期
                param.put("sqrq",rs.getStringNoTrim("modedatamodifydatetime"));
                // 报销流程名称
                param.put("bxlcmc",flowHeadLine);
                //报销流程记录id
                param.put("bxlcjlid",mapDtl[i].get("requestid"));
                // 流程编号
                String lcid = rs.getStringNoTrim("lcid");
                param.put("lcbh",lcid==null?"":lcid);
                param.put("bz","requestid:"+mapDtl[i].get("requestid")+" 第"+(i+1)+"行报销记录");
                //先删除本次报销流程的记录
                del.execute("delete from uf_jingfei_dt1 where bxlcjlid="+mapDtl[i].get("requestid"));
                // 新增一条明细
                rmcd.addJingfeiDetail(param);
                //break;
            }
        }

    }

    /**
     * TODO 添加主表报销明细
     * @param mapDtl
     * @param flowHeadLine
     * @param bxFlowId
     */
    public static void addDetail(Map<String,String> mapDtl,String flowHeadLine,String bxFlowId){
        //计算报销总金额
        Double bxjeSum=Double.valueOf(mapDtl.get("money"));
        // 添加一条明细
        String lcjlid = String.valueOf(mapDtl.get("lcjlid"));
        RecordSet rs = rmcd.queryJingfeiBylcjlId(lcjlid);
        while (rs.next()){
            Map<String,Object> param=new HashMap<>();
            param.put("mainid",rs.getInt("id"));
            param.put("bxje",bxjeSum);
            param.put("spzt",0);
            // 报销人
            String bxr = rs.getStringNoTrim("modedatamodifier");
            param.put("bxr",bxr);
            // 报销人部门
            RecordSet sbdw = rmcd.getSBKSById(Integer.valueOf(bxr));
            sbdw.next();
            String departmentmark = sbdw.getString("departmentmark");
            LOGGER.info("departmentmark----"+departmentmark);
            param.put("bxrbm", Tools.getbmyId(departmentmark));
            //经办部门
            param.put("jbbm","0");
            //经办人员
            param.put("jbry","0");
            //申请日期
            param.put("sqrq",rs.getStringNoTrim("modedatamodifydatetime"));
            // 报销流程名称
            param.put("bxlcmc",flowHeadLine);
            //报销流程记录id
            param.put("bxlcjlid",mapDtl.get("requestid"));
            // 流程编号
            String lcid = rs.getStringNoTrim("lcid");
            param.put("lcbh",lcid==null?"":lcid);
            param.put("bz","暂无备注");
            // 新增一条明细
            rmcd.addJingfeiDetail(param);
            break;
        }
    }

    /**
     * 经费金额冻结
     * @param map
     * @return
     */
    @POST
    @Path("/test")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String test(Map<String,Object> map){
       double je= (double) map.get("je");
       // requestId/bmjjzc/je
        RecordSet rs = new BudgeSourceDao().selectByReqIdAndBmjjzcAndOrderBy(map);
        double jeSum=0;
        RecordSetTrans rst=new RecordSetTrans();
        while (rs.next()){
            double syed = rs.getDouble("syed");
            String requestId = rs.getString("requestId");
            String bmjjzc = rs.getString("bmjjzc");
            int ysly = rs.getInt("ysly");
            if(je>=syed){
                je-=syed;
                String sql="update uf_jingfeilaiyuan set syed=0 where requestId=? and bmjjzc=? and ysly=?";
                try {
                    rst.executeUpdate(sql,requestId,bmjjzc,ysly);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                je-=syed;
                String sql="update uf_jingfeilaiyuan set syed=syed-? where requestId=? and bmjjzc=? and ysly=?";
                try {
                    rst.executeUpdate(sql,je,requestId,bmjjzc,ysly);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return JSON.toJSONString(Res.ok(200,""));
    }
    public static void main(String[] args) {
        String str="12.00";
        String substring = str.substring(0,str.indexOf("."));
        System.out.println(Integer.valueOf(substring));
    }
}
